package com.powernode.ajax.controller;

import com.powernode.ajax.pojo.Student;
import com.powernode.ajax.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;

@Controller
public class Ajax01Controller {
    @RequestMapping("/")
    public String homePage(){
        return "ajax1";
    }
    @RequestMapping("/check")
    public void check(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取用户名   xhr.send("uname="+username)    与请求参数保持一致
        String uname = request.getParameter("uname");
        Boolean flag = false;//布尔标记
        //连接数据库验证用户名是否存在
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/powernode","root","1234");
            //3.获取预编译的数据库操作对象
            String sql = "select id,username from t_user where username = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,uname);
            //4.执行SQL语句
            rs = ps.executeQuery();
            //5.处理结果集
            if (rs.next()) {
                //进来了，说明查到了一条记录，用户已存在
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //响应结果到浏览器
        PrintWriter out = response.getWriter();
        if(flag){
            //用户名已存在,不可用
            out.print("<font color='red'>对不起，用户名已存在</font>");
        }else {
            //用户名不存在，可以使用
            out.print("<font color='green'>用户名可以使用</font>");
        }

    }

    @RequestMapping("/ajax2")
    public String ajax2(){
        return "ajax2";
    }

    @RequestMapping("/display")
    public void display(HttpServletRequest request,HttpServletResponse response){
        response.setContentType("text/html;charset=UTF-8");
        //连接数据库，查询学员信息，拼接HTML代码，响应HTML代码到浏览器
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/powernode","root","1234");
            //3.获取预编译的数据库操作对象
            String sql = "select id,username,age,city from t_user ";
            ps = conn.prepareStatement(sql);
            //4.执行SQL语句
            rs = ps.executeQuery();
            //5.处理结果集
            //响应结果到浏览器
            PrintWriter out = response.getWriter();
            //StringBuilder json = new StringBuilder();
            //String jsonStr = "";
           // json.append("[");
            ArrayList<Student> students = new ArrayList<>();
            while (rs.next()){
               int id = rs.getInt("id");
               String username = rs.getString("username");
               int age = rs.getInt("age");
               String city = rs.getString("city");
//               out.print("    <tr>\n" +
//                       "      <td>"+id+"</td>\n" +
//                       "      <td>"+username+"</td>\n" +
//                       "      <td>"+age+"</td>\n" +
//                       "      <td>"+city+"</td>\n" +
//                       "    </tr>");
               //将以上程序拼接HTML，换成拼接JSON格式的字符串
//                json.append("{"+"\"id\""+":"+"\""+id+"\"" + "," +"\""+"username" + "\""+":"+"\""+username+ "\""+","+
//                        "\"age\""+":"+"\""+age+"\"" + "," +"\""+"city" + "\""+":"+"\""+city+ "\""+"},");
                Student student = new Student(id,username,age,city);
                students.add(student);
           }
//            json.deleteCharAt(jsonStr.length()-1);//删掉最后一个下标对应的字符
//            json.append("]");

            //将List集合转换成格式JSON字符串
            String jsonStr = JSON.toJSONString(students);
            //jsonStr = json.substring(0,json.length()-1)+"]";
            //[a,b)
            //str.substring(a,b)从下标a开始截，到下标b的前一个字符结束，不包含下标b
            out.print(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("/jsontest")
    public String jsontest(){
        return "jsontest";
    }

    @RequestMapping("/jsontest2")
    public String jsontest2(){
        return "jsontest2";
    }

    @RequestMapping("/xml_ajax")
    public String xml_ajax(){
        return "xml_ajax";
    }

    @RequestMapping("/ajax_xmlTest")
    public void ajax_xmlTest(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //不能写成text/html   发送的与响应的要对应
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        StringBuilder xml = new StringBuilder();
        xml.append("<students>");
        xml.append("<student>");
        xml.append("<name>zhangsan</name>");
        xml.append("<age>20</age>");
        xml.append("</student>");
        xml.append("<student>");
        xml.append("<name>lisi</name>");
        xml.append("<age>21</age>");
        xml.append("</student>");
        xml.append("</students>");
        out.print(xml);
    }

    @RequestMapping("/ajax_t_or_y")
    public String ajax_t_or_y(){
        return "ajax_t_or_y";
    }


    @RequestMapping("/ajax_t_or_y_test")
    public void ajax_t_or_y_test(HttpServletRequest request,HttpServletResponse response){

    }


    @RequestMapping("/testResponseBody")
    @ResponseBody
    public String testResponseBody(){
        //当处理器方法上添加了@ResponseBody，那么这个方法的返回值不再是逻辑视图名称
        //而是直接将字符串响应给浏览器了
        return "hello ajax";
    }

}
